package com.example.helloandroid;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class HelloAndroid extends Activity {
    private TextToSpeech textToSpeech;
    private boolean textToSpeechInitialized =false;
	private TextView mDateDisplay;
    private Button mPickDate;
    
    private int mYear;
    private int mMonth;
    private int mDay;

    static final int DATE_DIALOG_ID = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        
        mDateDisplay = (TextView) findViewById(R.id.TextView01);
        mPickDate = (Button) findViewById(R.id.Button01);

		textToSpeech = new TextToSpeech(HelloAndroid.this, new  TextToSpeech.OnInitListener() {
			
			public void onInit(int status) {
				textToSpeechInitialized = true;
				
			}
		});    
		textToSpeech.setLanguage(Locale.ITALIAN);
		textToSpeech.setSpeechRate(90);
        // add a click listener to the button
        mPickDate.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        ((Button)findViewById(R.id.SimpleListDemoBtn)).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
		    	startActivity(new Intent(HelloAndroid.this, TestListerActivity.class));
		    	//finish();				
			}
		});

        ((Button)findViewById(R.id.SpinButton02)).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
		    	startActivity(new Intent(HelloAndroid.this, TestSpinControl.class));
		    	//finish();				
			}
		});

        ((Button)findViewById(R.id.AutoCompleteBtn)).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
		    	startActivity(new Intent(HelloAndroid.this, TestAutoComplete.class));
		    	//finish();				
			}
		});

        ((Button)findViewById(R.id.FastListBtn)).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
		    	startActivity(new Intent(HelloAndroid.this, TestFasterDynamicList.class));
		    	//finish();				
			}
		});
        
        ((Button)findViewById(R.id.TabBtn)).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
		    	startActivity(new Intent(HelloAndroid.this, TestTab.class));
		    	//finish();				
			}
		}); 
        
        
        ((Button)findViewById(R.id.WeatherToastBtn)).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
		    	Toast.makeText(HelloAndroid.this, "Toast text example", Toast.LENGTH_LONG).show();
		    	String city = ((EditText) findViewById(R.id.CityText)).getText().toString();
		    	if (!"".equals(city))
		    		getForecast(city);
			}
		});     

        ((Button)findViewById(R.id.DialogBtn)).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
		    	new AlertDialog.Builder(HelloAndroid.this)
		    			.setTitle("Dialog title")
		    			.setMessage("Dialog proof")
		    			.setIcon(R.drawable.small_blue_ball)
		    			.setNeutralButton("Close", new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								Log.d(HelloAndroid.class.getName(), "Closing dialog");
								
							}
						})
		    			.show();
		    					
			}
		}); 
        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        // display the current date
        updateDisplay();
        
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        return null;
    }

    @Override
	protected void onResume() {
		super.onResume();
		Log.i("My Activity", "ON-RESUME");
	}
    
    

	@Override
	protected void onStart() {
		super.onStart();
		Log.i("My Activity", "ON-START");
	}

	// updates the date we display in the TextView
    private void updateDisplay() {
    	Log.i("My Activity", "PROVAAAAAAAAAAAAAAAAAAAAA");
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
    }

    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        menu.getItem(0).setIntent(new Intent(HelloAndroid.this, TestTab.class));
        Log.i("PROVA", "CDFCDGBVCGHJKKK");
        return true;
    }

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Log.i("PROVA", "featureId=" + featureId);
		return super.onMenuItemSelected(featureId, item);
	}

	private void getForecast(String city)
	{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet("http://meteo.libero.it/ricerca.php?cerca="+city+"&x=0&y=0");
		HttpGet getMethodGoogle = new HttpGet("http://www.google.com/m?action=chgloc&loc=roma,+italy&gl=us&source=android-launcher-search&client=ms-null&q=weather&hl=en");
//		http://uk.weather.yahoo.com/search/weather?p=milan,+italy
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		try {
			String responseBody = client.execute(getMethod, responseHandler);
			String responseBodyGoogle = client.execute(getMethodGoogle, responseHandler);
			
			String anchorGoogle = "/images/weather/";
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.parse(new InputSource(new StringReader(responseBodyGoogle)));
			NodeList imgNodeList = doc.getElementsByTagName("img");
			StringBuffer message = new StringBuffer();
			for (int ik=0; ik < imgNodeList.getLength(); ik++)
			{
				NamedNodeMap imgNodeMap = imgNodeList.item(ik).getAttributes();
				Node imgNode = imgNodeMap.getNamedItem("alt");
				if (ik ==1)
					message.append(imgNode.getNodeValue().trim()).append(" ");
				Log.d(HelloAndroid.class.getName(), imgNode.getNodeValue());
			}
			textToSpeech.setLanguage(Locale.ENGLISH);
						
			textToSpeech.speak("the weather forecast for today is " + message.toString(), TextToSpeech.QUEUE_ADD, null);
			Log.d(HelloAndroid.class.getName(), doc.getElementsByTagName("img").toString());
			
			// I have found the search page
			ArrayList<String> resultFindAnchor = new ArrayList<String>();
			ArrayList<Integer> positionCityAnchor = new ArrayList<Integer>();
			if (responseBody.indexOf("Hai cercato:") != -1)
			{
				Pattern pattern = Pattern.compile("\\Q<a\\E.*\\Qhref=\"\\E.*\\Q.php?id=\\E.*\\Q</a>\\E");
			    Matcher matcher = pattern.matcher(responseBody);				
			    int cycle = -1;
			    while (matcher.find()) {
			        String anchorCity = responseBody.substring(matcher.start(), matcher.end());
			        // Splitting
			        Log.d("PR", anchorCity);
			        if (anchorCity.toLowerCase().contains(city+"</a>"))
			        {
			        	cycle++;
			        	positionCityAnchor.add(new Integer(cycle));
			        }
			        resultFindAnchor.add(anchorCity);
			    }
			}
			for (Integer integer : positionCityAnchor) {
				Log.d("PR", resultFindAnchor.get(integer.intValue() -1) + resultFindAnchor.get(integer.intValue()));
			} 
			

			String dateMessage = 
				responseBody.substring(responseBody.indexOf("Oggi"), 
						responseBody.indexOf('<', responseBody.indexOf("Oggi")));
			
			String minTemp = 
				(responseBody.substring(responseBody.indexOf("Min: ") + 4, 
						responseBody.indexOf('<', responseBody.indexOf("Min:")) -1)).trim();	

			String maxTemp = 
				(responseBody.substring(responseBody.indexOf("Max: ") + 4, 
						responseBody.indexOf('<', responseBody.indexOf("Max:")) -1)).trim();	
			
			// Handle of prevision Time
			ArrayList<String> previsionTime = new ArrayList<String>();
			String anchor = "/c/i/quadrato.jpg";

			int start = 0;
			int end = 0;
			int numOfPeriodOfDay = 0; 
			while ((start = responseBody.indexOf(anchor, start)) != -1)
			{
				end = responseBody.indexOf('<', start);
				String msg = (responseBody.substring(start + anchor.length() + 2, end)).trim();
				msg = (msg.substring(0, msg.indexOf(" "))).trim();
				start = end; 
				if (CommonData.periodOfDay.Notte.name().equals(msg) && numOfPeriodOfDay != 0)
					break;
				previsionTime.add(msg);
				numOfPeriodOfDay++;
			}
			
			// Handle of prevision weather
			ArrayList<String> previsionWeather = new ArrayList<String>();
			String anchorIcon ="/c/i/icone/prev/";			
			start = 0;
			end = 0;
			while ((start = responseBody.indexOf(anchorIcon, start)) != -1)
			{
				end = responseBody.indexOf("</td>", responseBody.indexOf("<br>", start));
				String msg = (responseBody.substring(responseBody.indexOf("<br>", start) + 4, end)).trim();
				start = end; 
				previsionWeather.add(msg);
			}
			
			textToSpeech.setLanguage(Locale.ITALIAN);
			
			if (textToSpeechInitialized == false)
				Toast.makeText(HelloAndroid.this, "Text to speech not initialized", Toast.LENGTH_LONG).show();
			
			textToSpeech.speak(dateMessage, TextToSpeech.QUEUE_ADD, null);
			for (int ij = 0; ij < numOfPeriodOfDay; ij++)
			{
				textToSpeech.speak(previsionTime.get(ij), TextToSpeech.QUEUE_ADD, null);
				textToSpeech.speak(previsionWeather.get(ij), TextToSpeech.QUEUE_ADD, null);
			}
			textToSpeech.speak("La temperatura minima prevista oggi è di " + minTemp + ((minTemp.equals("1") || minTemp.equals("-1")) ? " grado" : " gradi"), TextToSpeech.QUEUE_ADD, null);
			textToSpeech.speak("La temperatura massima prevista oggi è di " + maxTemp + ((maxTemp.equals("1") || maxTemp.equals("-1")) ? " grado" : " gradi"), TextToSpeech.QUEUE_ADD, null);			

			Log.d(HelloAndroid.class.getName(),"########### FINISHED##########");
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FactoryConfigurationError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}